package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.article.service.ArticleService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
@Slf4j
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    @Autowired
    private Configuration configuration;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private ArticleService articleService;
    /**
     * 生成静态文件,上传minio
     *
     * @param apArticle
     * @param content
     */
    @Override
    @Async
    public void buildSrtivleToMinio(ApArticle apArticle, String content) {
        try {
            if (StringUtils.isNotBlank(content)) {
                //生成模板
                StringWriter out = new StringWriter();
                Template template = configuration.getTemplate("article.ftl");
                Map<String, Object> map = new HashMap<>();
                map.put("content", JSONArray.parseArray(content));
                //合成
                template.process(map, out);
                ByteArrayInputStream is = new ByteArrayInputStream(out.toString().getBytes());
                //上传
                String path = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", is);
                //修改Article中的静态资源路径
                ApArticle article = articleService.getOne(Wrappers.<ApArticle>lambdaQuery().eq(ApArticle::getId, apArticle.getId()));
                article.setStaticUrl(path);
                articleService.updateById(article);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
        }

